import pymysql
from pymysql.cursors import DictCursor
from backend.utils.db import get_db_connection

class AddressService:
    def get_user_orders_with_address(self, user_id):
        try:
            # 修复：正确使用数据库连接上下文管理器
            with get_db_connection() as (cursor, conn):
                sql = """
                    SELECT o.order_id, o.shipping_address, o.contact_phone, p.name AS product_name
                    FROM orders o
                    JOIN products p ON o.product_id = p.product_id
                    WHERE o.user_id = %s
                """
                cursor.execute(sql, (user_id,))
                return cursor.fetchall()
        except Exception as e:
            print(f"获取用户订单失败: {e}")
            import traceback
            traceback.print_exc()  # 添加详细错误追踪
            return []

    def get_editable_orders(self, user_id):
        """获取用户可修改地址的订单（已付款未发货）"""
        try:
            with get_db_connection() as (cursor, conn):
                sql = """
                      SELECT order_id, product_name, shipping_address, status
                      FROM orders
                      WHERE user_id = %s \
                        AND status = '已付款'
                      ORDER BY order_time DESC \
                      """
                cursor.execute(sql, (user_id,))
                return cursor.fetchall()
        except Exception as e:
            print(f"获取可修改地址订单失败: {e}")
            return []

    def update_shipping_address(self, user_id, order_id, new_address):  # 添加 user_id 参数
        """修改订单收货地址，仅允许修改已付款但未发货的订单"""
        try:
            with get_db_connection() as (cursor, conn):
                # 先检查订单是否属于当前用户且状态为已付款
                check_sql = """
                            SELECT status
                            FROM orders
                            WHERE order_id = %s
                              AND user_id = %s \
                            """
                cursor.execute(check_sql, (order_id, user_id))
                order = cursor.fetchone()

                if not order:
                    return False, "订单不存在或不属于当前用户"

                if order['status'] != '已付款':
                    return False, "只有已付款的订单可以修改收货地址"

                # 更新地址
                update_sql = """
                             UPDATE orders
                             SET shipping_address = %s
                             WHERE order_id = %s
                               AND user_id = %s
                             """
                cursor.execute(update_sql, (new_address, order_id, user_id))
                conn.commit()

                if cursor.rowcount == 0:
                    return False, "地址更新失败，请检查订单信息"

                return True, "地址更新成功"
        except Exception as e:
            conn.rollback()
            print(f"更新收货地址失败: {e}")
            return False, f"更新失败: {str(e)}"
